//
//  TstDirectVC.swift
//  TstChat
//
//  Created by wanghui on 2018/5/18.
//  Copyright © 2018年 daerwei. All rights reserved.
//

import UIKit
import MJRefresh
import Toast_Swift

class TstDirectVC: UIViewController {
    var msg:ChatMessage!
    
    lazy var tableView:UITableView = {
        let tableView = UITableView(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height), style: .plain)
        tableView.separatorStyle = .singleLine
        tableView.tableFooterView = UIView.init(frame: CGRect.zero)
        tableView.dataSource = self
        tableView.delegate = self
        tableView.register(TstAddressbookCell.self, forCellReuseIdentifier: "addressbookCell")
        tableView.rowHeight = 55
        tableView.backgroundColor = RGBA(r: 241/255, g: 240/255, b: 245/255, a: 1)
        tableView.tableFooterView = UIView(frame: CGRect.zero)
        
        //设置索引的字体颜色 (默认是蓝色)
        tableView.sectionIndexColor = UIColor.black.withAlphaComponent(0.6)   //可以改变索引字体的颜色
        
        return tableView
    }()
    
    var contactList = [ChatContact]()
    let collation = UILocalizedIndexedCollation.current()
    var sectionsArray: [[ChatContact]] = [[ChatContact]]()
    let string1 = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1527496544456&di=164baddcaed475821f8043f0e1e43a4f&imgtype=0&src=http%3A%2F%2Fimgsrc.baidu.com%2Fimgad%2Fpic%2Fitem%2F3801213fb80e7beca9004ec5252eb9389b506b38.jpg"
    let string2 = "https://goss4.vcg.com/creative/vcg/800/version23/VCG4194433129.jpg"
    
    var imgURL = [String]()
    
    let page: NSInteger = 0
    
    //      func setData(){
    //        for _ in 0...10000 {
    //            let a = arc4random_uniform(UInt32(collation.sectionTitles.count))
    //            let b = collation.sectionTitles[Int(a)]
    //            self.contactList.append(ChatContact(userId: 0, displayName: "\(b)dfasdfasdf", tag: "创始人"))
    //        }
    //        setSection()
    //    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.view.makeToastActivity(.center)
        DispatchQueue.global().async {
            
            self.loadData()
            self.setSection()
            DispatchQueue.main.async {
                self.tableView.reloadData()
                self.view.hideToastActivity()
            }
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
    }
    
    let service = ContactService()
    
    func loadData() {
        DispatchQueue.global().async {
            self.contactList = self.service.getDirectContactList()
            if self.contactList.count > 0 {
                self.setSection()
                DispatchQueue.main.async {
                    self.tableView.reloadData()
                }
            }
        }
    }
    
    func setUI() {
        // Do any additional setup after loading the view.
        self.title = NSLocalizedString("直系",comment:"直系")
        self.view.backgroundColor =  RGBA(r: 241/255, g: 240/255, b: 245/255, a: 1)
        self.view.addSubview(tableView)
        
        //设置导航栏的背景色
        //        self.navigationController?.navigationBar.barTintColor = UIColor.black
        //    self.navigationController?.navigationBar.barStyle = .black
        //      self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
        //
        //设置导航栏左侧的按钮
        // 设置返回按钮的样式
        self.navigationController?.navigationBar.tintColor = UIColor.white     // 设置返回标识器的颜色
        self.navigationItem.backBarButtonItem?.setTitleTextAttributes([.foregroundColor: UIColor.white], for: .normal)  // 返回按钮
    }
    
    @objc func buttonTap(button:UIButton) {
        self.navigationController?.popViewController(animated: true)
    }
    
    func setSection(){
        //        self.collation = UILocalizedIndexedCollation.current()
        let sectionTitlesCount = self.collation.sectionTitles.count
        print(sectionTitlesCount)
        //临时数据，存放section对应的userObjs数组数据
        var newSectionsArray = [[ChatContact]]()
        
        //设置sections数组初始化：元素包含userObjs数据的空数据
        for _ in 0 ..< sectionTitlesCount {
            let array = [ChatContact]()
            newSectionsArray.append(array)
        }
        //将用户数据进行分类，存储到对应的sesion数组中
        
        for contact in contactList {
            //根据timezone的localename，获得对应的的section number
            let sectionNumber = self.collation.section(for: contact, collationStringSelector: #selector(getter: ChatContact.displayName))
            //            let headerString = self.collation.sectionTitles[sectionNumber]
            //            if !indexArray.contains(headerString) {
            //                indexArray.append(headerString)
            //            }
            //
            //获得section的数组
            var sectionBeans = newSectionsArray[sectionNumber]
            
            //添加内容到section中
            sectionBeans.append(contact)
            
            // swift 数组是值类型，要重新赋值
            newSectionsArray[sectionNumber] = sectionBeans
        }
        
        //排序，对每个已经分类的数组中的数据进行排序，如果仅仅只是分类的话可以不用这步
        for i in 0 ..< sectionTitlesCount {
            let beansArrayForSection = newSectionsArray[i]
            //获得排序结果
            let sortedBeansArrayForSection = collation.sortedArray(from: beansArrayForSection, collationStringSelector:  #selector(getter: ChatContact.displayName))
            //替换原来数组
            newSectionsArray[i] = sortedBeansArrayForSection as! [ChatContact]
        }
        sectionsArray = newSectionsArray
    }
}

extension TstDirectVC:UITableViewDataSource, UITableViewDelegate {
    internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let addressbookCell = "addressbookCell"
        let cell = tableView.dequeueReusableCell(withIdentifier: addressbookCell, for: indexPath) as! TstAddressbookCell
        let userNameInSection = sectionsArray[indexPath.section]
        let contact = userNameInSection[indexPath.row]
        cell.selectionStyle = .none
        cell.nameLabel.text = contact.displayName
        //            cell.tagbutton.setTitle(contact.tag, for: .normal)
        cell.headimage.kf.setImage(with: Common.avatarUrl(contact.avatar ?? "") ?? URL(string: "localhost")!, placeholder: UIImage.init(named: "defaultAvatar"))
        //            cell.tagbutton.isHidden = false
        return cell
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.collation.sectionTitles.count
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if sectionsArray.count == 0 {
            return nil
        }
        let beanInSection = sectionsArray[section]
        if beanInSection.count == 0 {
            return nil
        }else {
            let customview = UIView.init(frame: CGRect.init(x: 10, y: 0, width: UIScreen.main.bounds.size.width, height: 23))
            let label = UILabel.init(frame: CGRect.zero)
            label.backgroundColor = .clear
            label.isOpaque = false
            label.textColor = UIColor.black.withAlphaComponent(0.5)
            label.font = UIFont.systemFont(ofSize: 13)
            label.frame = CGRect.init(x: 10, y: 0, width: 50, height: 23)
            if sectionsArray.count == 0 {
                label.text = ""
            }
            let beansInSection = sectionsArray[section]
            if (beansInSection as AnyObject).count <= 0 {
                label.text = ""
            }
            let headerString = collation.sectionTitles[section]
            label.text = headerString
            customview.addSubview(label)
            customview.backgroundColor =  RGBA(r: 241/255, g: 240/255, b: 245/255, a: 1)
            return customview
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        if sectionsArray.count > 0 {
            let beanInSection = sectionsArray[section]
            if beanInSection.count == 0 {
                return 0
            }else {
                return 23;
            }
            
        } else {
            return 0
        }
        
        
        //        let beanInSection = sectionsArray[section]
        //        if beanInSection.count == 0 {
        //            return 0
        //        }else {
        //            return 23;
        //        }
    }
    
    //设置索引标题
    func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        return collation.sectionTitles
    }
    
    //关联搜索
    func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
        if index == 0{
            tableView.setContentOffset(CGPoint.zero, animated: false)
            return 0
        }
        return collation.section(forSectionIndexTitle: index)
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if sectionsArray.count == 0 {
            return 0
        }
        let beanInSection = sectionsArray[section]
        return beanInSection.count
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if (msg != nil) {
            let sendVC = sendToVC()
            sendVC.msg = msg
            let session = sectionsArray[indexPath.section][indexPath.row]
            sendVC.sessionServerId = session.userId
            sendVC.chatcontact = session
            sendVC.type = 0 //
            
            sendVC.definesPresentationContext = true;
            sendVC.modalPresentationStyle = .overFullScreen
            sendVC.modalTransitionStyle = .crossDissolve
            self.present(sendVC, animated: true)
        }else {
            let session = sectionsArray[indexPath.section][indexPath.row]
            let chatvc = ChatVC()
            chatvc.title = session.displayName
            chatvc.chatType = ChatType.p2p
            chatvc.sessionServerId = session.userId
            chatvc.sessionName = session.displayName
            chatvc.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(chatvc, animated: true)
        }
    }
}
